package com.xjc.study.operatingexamination.od.computertest;

import java.util.Scanner;

/**
 * @author xujiucheng
 * @Description: 华为OD机试-周末爬山
 * 周末小明准备去爬山锻炼，0代表平地，山的高度使用1到9来表示，小明每次爬山或下山高度只能相差k及k以内，
 * 每次只能上下左右一个方向上移动一格，小明从左上角(0,0)位置出发
 * 第一行输入m n k(空格分隔)。代表m*n的二维山地图，k为小明每次爬山或下山高度差的最大值
 * 然后接下来输入山地图，一共m行n列，均以空格分隔。取值范围: 0< m <= 500  0<n<=500   0<k<5
 *
 * 输出描述
 * 请问小明能爬到的最高峰多高，到该最高峰的最短步数，输出以空格分隔。
 * 同高度的山峰输出较短步数.，如果没有可以爬的山峰，则高度和步数都返回0
 *
 * 示例1：
 * 输入
 * 5 4 1
 * 0 1 2 0
 * 1 0 0 0
 * 1 0 1 2
 * 1 3 1 0
 * 0 0 0 9
 *
 * 输出
 * 2 2
 *
 * 说明:根据山地图可知，能爬到的最高峰在(0,2)位置，高度为2，最短路径为(0,0)-(0,1)-(0,2)，最短步数为2。
 *
 * 示例2：
 * 输入
 * 5 4 3
 * 0 0 0 0
 * 0 0 0 0
 * 0 9 0 0
 * 0 0 0 0
 * 0 0 0 9
 *
 * 输出
 * 0 0
 *
 * 说明:根据山地图可知，每次爬山距离3，无法爬到山峰上，步数为0.
 * @date 2023-10-08 13:06
 */
public class Mountaineering {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        int k = scanner.nextInt();

        int[][] grid = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                grid[i][j] = scanner.nextInt();
            }
        }

        int maxHeight = 0;
        int minSteps = 0;

        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] > 0 && !visited[i][j]) {
                    int[] result = dfs(grid, i, j, k, visited);
                    int height = result[0];
                    int steps = result[1];
                    if (height > maxHeight || (height == maxHeight && steps < minSteps)) {
                        maxHeight = height;
                        minSteps = steps;
                    }
                }
            }
        }

        System.out.println(maxHeight + " " + minSteps);
    }

    public static int[] dfs(int[][] grid, int row, int col, int k, boolean[][] visited) {
        int m = grid.length;
        int n = grid[0].length;

        if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] || grid[row][col] == 0) {
            return new int[]{0, 0};
        }

        visited[row][col] = true;

        int maxHeight = 0;
        int maxSteps = 0;
        for (int i = -k; i <= k; i++) {
            for (int j = -k; j <= k; j++) {
                if (Math.abs(i) + Math.abs(j) <= k) {
                    int[] result = dfs(grid, row + i, col + j, k, visited);
                    int height = result[0];
                    int steps = result[1];
                    if (height > maxHeight || (height == maxHeight && steps < maxSteps)) {
                        maxHeight = height;
                        maxSteps = steps;
                    }
                }
            }
        }

        visited[row][col] = false;

        return new int[]{Math.max(maxHeight, grid[row][col]), maxSteps + 1};
    }
}
